package com.xz.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.method.P;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author XZ
 * @create 2021-12-26 15:58
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //1.使用 SQL 语句根据用户名查询用户对象
        String sql ="SELECT id,loginacct,userpswd,username,email FROM t_admin WHERE loginacct=?;";
        Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql, s);
        String loginacct = resultMap.get("loginacct").toString();
        String userpswd = resultMap.get("userpswd").toString();
        //2.给Admin设置角色权限信息：方式一
        List<GrantedAuthority> list = AuthorityUtils.createAuthorityList("ADMIN", "ROLE_学徒");
        // 2.给Admin设置角色权限信息：方式二
//        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
//        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
//        authorities.add(new SimpleGrantedAuthority("UPDATE"));

        // 3.把admin对象和authorities封装到UserDetails中
        User user = new User(loginacct, userpswd, list);
        return user;
    }
}
